import React, { useRef, useEffect, useState, useCallback } from 'react'
import { Card, Row, Col, Slider, Typography } from 'antd'
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler } from 'chart.js'
import { Line, Scatter } from 'react-chartjs-2'
import { useWebSocket } from '../../hooks/useWebSocket'
import { Utils } from '../../utils'
import './DataCharts.css'

const { Text } = Typography

// 注册Chart.js组件
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
)

const DataCharts = () => {
  const { angleHistory, positionHistory } = useWebSocket()
  const [xyDuration, setXyDuration] = useState(0.5)
  const angleChartRef = useRef(null)
  const xyChartRef = useRef(null)

  // 角度图表配置
  const angleChartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    animation: { duration: 0 },
    plugins: {
      legend: { display: false },
      tooltip: {
        mode: 'index',
        intersect: false,
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        titleColor: '#ffffff',
        bodyColor: '#ffffff',
        borderColor: '#4fc3f7',
        borderWidth: 1
      }
    },
    scales: {
      x: {
        title: { 
          display: true, 
          text: '时间 (s)',
          color: '#bbdefb'
        },
        ticks: { 
          color: '#bbdefb', 
          maxTicksLimit: 8 
        },
        grid: {
          color: 'rgba(187, 222, 251, 0.2)'
        }
      },
      y: {
        title: { 
          display: true, 
          text: '角度 (°)',
          color: '#bbdefb'
        },
        ticks: { 
          color: '#bbdefb' 
        },
        grid: {
          color: 'rgba(187, 222, 251, 0.2)'
        },
        min: -30,
        max: 30
      }
    },
    interaction: {
      mode: 'nearest',
      axis: 'x',
      intersect: false
    }
  }

  // XY轨迹图表配置
  const xyChartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    animation: { duration: 0 },
    plugins: {
      legend: { display: false },
      tooltip: {
        mode: 'point',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        titleColor: '#ffffff',
        bodyColor: '#ffffff',
        borderColor: '#ff9800',
        borderWidth: 1,
        callbacks: {
          title: () => '位置',
          label: (context) => `X: ${context.parsed.x.toFixed(1)}, Y: ${context.parsed.y.toFixed(1)}`
        }
      }
    },
    scales: {
      x: {
        title: { 
          display: true, 
          text: 'Y 像素',
          color: '#bbdefb'
        },
        ticks: { 
          color: '#bbdefb' 
        },
        grid: {
          color: 'rgba(187, 222, 251, 0.2)'
        },
        min: -100,
        max: 100
      },
      y: {
        title: { 
          display: true, 
          text: 'X 像素',
          color: '#bbdefb'
        },
        ticks: { 
          color: '#bbdefb' 
        },
        grid: {
          color: 'rgba(187, 222, 251, 0.2)'
        },
        min: -100,
        max: 100
      }
    }
  }

  // 处理角度数据
  const getAngleChartData = useCallback(() => {
    if (!angleHistory || angleHistory.length === 0) {
      return {
        labels: [],
        datasets: [{
          label: '角度 (°)',
          data: [],
          borderColor: '#42a5f5',
          backgroundColor: 'rgba(66,165,245,0.08)',
          pointRadius: 0,
          borderWidth: 2,
          tension: 0.2,
          fill: true
        }]
      }
    }

    const t0 = angleHistory[0].time
    const labels = angleHistory.map(d => (d.time - t0).toFixed(2))
    const data = angleHistory.map(d => d.angle)

    return {
      labels,
      datasets: [{
        label: '角度 (°)',
        data,
        borderColor: '#42a5f5',
        backgroundColor: 'rgba(66,165,245,0.08)',
        pointRadius: 0,
        borderWidth: 2,
        tension: 0.2,
        fill: true
      }]
    }
  }, [angleHistory])

  // 处理XY轨迹数据
  const getXyChartData = useCallback(() => {
    if (!positionHistory || positionHistory.length === 0) {
      return {
        datasets: [{
          label: '轨迹',
          data: [],
          borderColor: '#ff9800',
          backgroundColor: '#ff9800',
          pointRadius: 3,
          showLine: false,
          fill: false
        }]
      }
    }

    const tmax = positionHistory[positionHistory.length - 1].time
    const tmin = tmax - xyDuration
    const filtered = positionHistory.filter(d => d.time >= tmin)
    const data = filtered.map(d => ({ x: d.y, y: d.x }))

    return {
      datasets: [{
        label: '轨迹',
        data,
        borderColor: '#ff9800',
        backgroundColor: '#ff9800',
        pointRadius: 3,
        showLine: false,
        fill: false
      }]
    }
  }, [positionHistory, xyDuration])

  // 更新角度图表的Y轴范围
  const updateAngleChartScale = useCallback(() => {
    if (!angleHistory || angleHistory.length === 0) return

    const maxabs = Math.max(10, Math.ceil(Math.max(...angleHistory.map(d => Math.abs(d.angle))) / 5) * 5)
    
    if (angleChartRef.current) {
      const chart = angleChartRef.current
      chart.options.scales.y.min = -maxabs
      chart.options.scales.y.max = maxabs
      chart.update('none')
    }
  }, [angleHistory])

  // 更新XY图表的坐标轴范围
  const updateXyChartScale = useCallback(() => {
    if (!positionHistory || positionHistory.length === 0) return

    const tmax = positionHistory[positionHistory.length - 1].time
    const tmin = tmax - xyDuration
    const filtered = positionHistory.filter(d => d.time >= tmin)

    let maxabsX = 100, maxabsY = 100

    if (filtered.length > 0) {
      maxabsX = Math.max(50, Math.ceil(Math.max(...filtered.map(d => Math.abs(d.x))) / 50) * 50)
      maxabsY = Math.max(50, Math.ceil(Math.max(...filtered.map(d => Math.abs(d.y))) / 50) * 50)
    }

    if (xyChartRef.current) {
      const chart = xyChartRef.current
      chart.options.scales.x.min = -maxabsY
      chart.options.scales.x.max = maxabsY
      chart.options.scales.y.min = -maxabsX
      chart.options.scales.y.max = maxabsX
      chart.update('none')
    }
  }, [positionHistory, xyDuration])

  // 处理XY持续时间滑块变化
  const handleXyDurationChange = useCallback((value) => {
    setXyDuration(value)
  }, [])

  // 更新图表
  useEffect(() => {
    updateAngleChartScale()
  }, [angleHistory, updateAngleChartScale])

  useEffect(() => {
    updateXyChartScale()
  }, [positionHistory, xyDuration, updateXyChartScale])

  return (
    <div className="data-charts">
      <Row gutter={[0, 16]}>
        {/* 角度-时间曲线 */}
        <Col span={24}>
          <Card 
            title="角度-时间曲线" 
            size="small"
            className="chart-card"
          >
            <div className="chart-container">
              <Line 
                ref={angleChartRef}
                data={getAngleChartData()}
                options={angleChartOptions}
              />
            </div>
          </Card>
        </Col>

        {/* 小球XY位置轨迹 */}
        <Col span={24}>
          <Card 
            title="小球XY位置轨迹" 
            size="small"
            className="chart-card"
          >
            <div className="chart-container">
              <Scatter 
                ref={xyChartRef}
                data={getXyChartData()}
                options={xyChartOptions}
              />
            </div>
            <div className="chart-controls">
              <div className="control-item">
                <Text style={{ color: '#94a3b8', fontSize: '12px' }}>
                  显示时长(秒): <span style={{ color: '#ffffff', fontWeight: 'bold' }}>
                    {Utils.formatNumber(xyDuration, 1)}
                  </span>
                </Text>
                <Slider
                  min={0.1}
                  max={2.0}
                  step={0.1}
                  value={xyDuration}
                  onChange={handleXyDurationChange}
                  tooltip={{
                    formatter: (value) => `${Utils.formatNumber(value, 1)}秒`,
                    placement: 'top'
                  }}
                  trackStyle={{ 
                    background: 'linear-gradient(90deg, #ff9800, #f57c00)' 
                  }}
                  handleStyle={{
                    borderColor: '#ff9800',
                    backgroundColor: '#ffffff',
                    boxShadow: '0 2px 8px rgba(255, 152, 0, 0.3)'
                  }}
                  railStyle={{
                    backgroundColor: 'rgba(255, 255, 255, 0.2)'
                  }}
                />
              </div>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default DataCharts
